package activity.setting.PlanVideo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.hichip.callback.ICameraIOSessionCallback;
import com.hichip.campro.R;
import com.hichip.content.HiChipDefines;
import com.hichip.control.HiCamera;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;

import activity.AllAdapter.RepeatTimeAdapter;
import base.HiActivity;
import bean.CardBean;
import bean.MyCamera;
import bean.RepeatTimeBean;
import bean.TimeArrayBean;
import butterknife.BindView;
import common.HiDataValue;
import common.TitleView;
import utils.HiToast;

public class AddTimeDomainActivity extends HiActivity implements View.OnClickListener, ICameraIOSessionCallback {
    @BindView(R.id.title) TitleView title;
    @BindView(R.id.ll_start_time) LinearLayout ll_start_time;
    @BindView(R.id.ll_end_time) LinearLayout ll_end_time;
    @BindView(R.id.tv_start_time) TextView tv_start_time;
    @BindView(R.id.tv_end_time) TextView tv_end_time;
    @BindView(R.id.tv_confim_add) TextView tv_confim_add;
    @BindView(R.id.tv_week) TextView tv_week;
    private ArrayList<TimeArrayBean> mBeans;
    private ArrayList<TimeArrayBean> mCopyBeans;
    private String mCurrentTitle;
    private MyCamera mMyCamera;
    private HiChipDefines.HI_P2P_QUANTUM_TIME quantum_time;


    @Override
    protected int setLayoutId() {
        return R.layout.activity_add_time_domain;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        getIntentData();
        initViewAndData();
        setOnListeners();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mMyCamera != null) {
            mMyCamera.registerIOSessionListener(this);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mMyCamera != null) {
            mMyCamera.unregisterIOSessionListener(this);
        }
    }


    private void setOnListeners() {
        ll_start_time.setOnClickListener(this);
        ll_end_time.setOnClickListener(this);
        tv_confim_add.setOnClickListener(this);
    }

    private void initViewAndData() {
        title.setTitle(getString(R.string.add_domain));
        title.setButton(TitleView.NAVIGATION_BUTTON_LEFT);
        title.setNavigationBarButtonListener(new TitleView.NavigationBarButtonListener() {
            @Override
            public void OnNavigationButtonClick(int which) {
                switch (which) {
                    case TitleView.NAVIGATION_BUTTON_LEFT:
                        finish(1);
                        break;
                }
            }
        });

        for (int i = 0; i <= 48; i++) {
            if (i < 48) {
                cardItems.add(new CardBean(i, jToStr(i)));
            } else if (i == 48) {
                cardItems.add(new CardBean(i, "23:59"));
            }
        }

    }

    private void getIntentData() {
        String str_uid = getIntent().getStringExtra(HiDataValue.EXTRAS_KEY_UID);
        if (!TextUtils.isEmpty(str_uid)) {
            for (MyCamera camera : HiDataValue.CameraList) {
                if (str_uid.equals(camera.getUid())) {
                    this.mMyCamera = camera;
                    break;
                }
            }
        }
        mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_REC_AUTO_SCHEDULE, new byte[0]);
        mBeans = getIntent().getParcelableArrayListExtra("beans");
        mCopyBeans = mBeans;
        StringBuffer sb = new StringBuffer();
        if (mBeans == null || mBeans.size() < 1) {
            finish();
            return;
        }
        Collections.sort(mBeans);
        for (int i = 0; i < mBeans.size(); i++) {
            TimeArrayBean bean = mBeans.get(i);
            String title = "";
            switch (bean.title) {
                case 0:
                    title = getString(R.string.sunday);
                    break;
                case 1:
                    title = getString(R.string.monday);
                    break;
                case 2:
                    title = getString(R.string.tuesday);
                    break;
                case 3:
                    title = getString(R.string.wednesday);
                    break;
                case 4:
                    title = getString(R.string.thursday);
                    break;
                case 5:
                    title = getString(R.string.friday);
                    break;
                case 6:
                    title = getString(R.string.saturday);
                    break;
            }
            sb.append(title + " ");
        }
        mCurrentTitle = sb.toString();
        tv_week.setText(mCurrentTitle);

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_start_time:
                //开始时间选择器
                mPv_time = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        String tx = cardItems.get(options1).getPickerViewText();
                        tv_start_time.setText(tx);
                    }
                }).setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        TextView tv_add = v.findViewById(R.id.tv_add);
                        tv_add.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPv_time.returnData();
                                mPv_time.dismiss();
                            }
                        });

                    }
                }).isDialog(true).build();
                mPv_time.setPicker(cardItems);//添加数据
                mPv_time.show();
                break;
            case R.id.ll_end_time:
                //结束时间选择器
                mPv_time = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        String tx = cardItems.get(options1).getPickerViewText();
                        tv_end_time.setText(tx);
                    }
                }).setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        TextView tv_record_time = v.findViewById(R.id.tv_record_time);
                        tv_record_time.setText(getString(R.string.end_record_time));

                        TextView tv_add = v.findViewById(R.id.tv_add);
                        tv_add.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPv_time.returnData();
                                mPv_time.dismiss();
                            }
                        });

                    }
                }).isDialog(true).build();
                mPv_time.setPicker(cardItems);//添加数据
                mPv_time.show();
                break;
            case R.id.tv_confim_add:
                handAdd();
//                handApplication();
                break;
        }
    }


    private void handAdd() {
        if (repeatTimeBeans != null) {
            repeatTimeBeans.clear();
        }
        String strStart = tv_start_time.getText().toString();
        String strEnd = tv_end_time.getText().toString();
        mStartEnd = strStart + "-" + strEnd;
        try {
            Date dateStart = sdf.parse(strStart);
            mStartTime = dateToMinute(dateStart);
            Date dateEnd = sdf.parse(strEnd);
            mEndTime = dateToMinute(dateEnd);
            if (dateToMinute(dateStart) >= dateToMinute(dateEnd)) {
                HiToast.showToast(AddTimeDomainActivity.this, getString(R.string.tips_stanotend));
            } else {
                //准备数据源 看看是否有重复时间段
                for (int i = 0; i < mBeans.size(); i++) {
                    TimeArrayBean bean = mBeans.get(i);
                    if (bean.mIsAllDay) {
                        repeatTimeBeans.add(new RepeatTimeBean(bean.title, "00:00-23:59", true));
                    } else {
                        ArrayList<String> strs = bean.getArrs();
                        for (String str : strs) {
                            String[] strings = str.split("-");
                            String strSt = strings[0];
                            String strEn = strings[1];
                            long beanStart = dateToMinute(sdf.parse(strSt));
                            long beanEnd = dateToMinute(sdf.parse(strEn));
                            long addStart = dateToMinute(dateStart);
                            long addEnd = dateToMinute(dateEnd);
                            Log.i("tedu", "--beanStart--:" + beanStart + "--beanEnd--:" + beanEnd + "--addStart--:" + addStart + "--addEnd--:" + addEnd);
                            if (beanStart <= addStart && beanEnd >= addEnd) {//交集
                                repeatTimeBeans.add(new RepeatTimeBean(bean.title, str, false));
                            }
                        }
                    }
                }
                if (repeatTimeBeans != null && repeatTimeBeans.size() > 0) {//有重复时间段
                    handPup(mStartEnd);
                } else {
                    for (int j = 0; j < mBeans.size(); j++) {
                        TimeArrayBean bean = mBeans.get(j);
                        for (int i = 0; i < bean.arrs.size(); i++) {
                            String str = bean.arrs.get(i);
                            String[] strings = str.split("-");
                            String strSt = strings[0];
                            String strEn = strings[1];
                            long beanStart = dateToMinute(sdf.parse(strSt));
                            long beanEnd = dateToMinute(sdf.parse(strEn));
                            long addStart = dateToMinute(dateStart);//添加的
                            long addEnd = dateToMinute(dateEnd);
                            if (addStart >= beanStart && addStart <= beanEnd && addEnd >= beanEnd) {
                                String myStr = strSt + "-" + strEnd;
                                bean.arrs.remove(i);
                                mStartEnd = myStr;
                            }
                        }
                        if (mStartEnd.equals("00:00-23:59")) {
                            bean.mIsAllDay = true;
                        }
                        bean.getArrs().add(mStartEnd);
                    }
                    Intent date = new Intent();
                    date.putParcelableArrayListExtra("beans", mBeans);

                    if (quantum_time != null) {
                        handApplication(mBeans);
                    }

                    setResult(Activity.RESULT_OK, date);
                    finish();
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void handApplication(ArrayList<TimeArrayBean> beans) {
        for (TimeArrayBean bean : beans) {
            int i = bean.getTitle();
            for (int j = 0; j < 48; j++) {
                quantum_time.sDayData[i][j] = 78;//关
                if (bean.mIsAllDay) {
                    quantum_time.sDayData[i][j] = 80;
                    continue;
                }
                if (bean.getArrs() != null && bean.getArrs().size() < 1 && !bean.mIsAllDay) {
                    quantum_time.sDayData[i][j] = 78;
                    continue;
                }
                for (String strArr : bean.arrs) {
                    String[] strings = strArr.split("-");
                    String strStar = strings[0];
                    String strEnd = strings[1];
                    try {
                        int indexStar = dateToMinute(sdf.parse(strStar)) / 30;
                        int indexEnd = dateToMinute(sdf.parse(strEnd)) / 30 - 1;
                        if (strEnd.equals("23:59")) {
                            indexEnd = 47;
                        }
                        if (j >= indexStar && j <= indexEnd) {
                            quantum_time.sDayData[i][j] = 80;//开
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        //showjuHuaDialog();
        mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_REC_AUTO_SCHEDULE, quantum_time.parseContent());
    }

    private ArrayList<RepeatTimeBean> mPupBeans = new ArrayList<>();
    private int mStartTime;
    private int mEndTime;
    private String mStartEnd;

    private void handPup(String strTime) {
        View customView = View.inflate(AddTimeDomainActivity.this, R.layout.pup_repeat_time, null);
        PopupWindow popupWindow = new PopupWindow(customView);
        ColorDrawable cd = new ColorDrawable(-000);
        popupWindow.setBackgroundDrawable(cd);
        popupWindow.setFocusable(true);
        popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.showAtLocation(customView, Gravity.CENTER, 0, 0);

        ListView lv_pup = customView.findViewById(R.id.lv_pup);

        //准备数据源
        RepeatTimeAdapter adapter = new RepeatTimeAdapter(AddTimeDomainActivity.this, repeatTimeBeans);
        lv_pup.setAdapter(adapter);
        if (mPupBeans != null) {
            mPupBeans.clear();
        }
        mPupBeans.addAll(repeatTimeBeans);
        lv_pup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RepeatTimeAdapter.ViewHolder holder = (RepeatTimeAdapter.ViewHolder) view.getTag();
                if (holder.cb_time.isChecked()) {
                    holder.cb_time.setChecked(false);
                    if (repeatTimeBeans != null && repeatTimeBeans.size() > position) {
                        mPupBeans.remove(repeatTimeBeans.get(position));
                    }
                    if (mBeans != null && mBeans.size() > position) {
                        mCopyBeans.remove(mBeans.get(position));
                    }
                } else {
                    holder.cb_time.setChecked(true);
                    if (repeatTimeBeans != null && repeatTimeBeans.size() > position) {
                        mPupBeans.add(repeatTimeBeans.get(position));
                    }
                    if (mBeans != null && mBeans.size() > position) {
                        mCopyBeans.add(mBeans.get(position));
                    }
                }
            }
        });

        TextView tv_pup_one = customView.findViewById(R.id.tv_pup_one);
        tv_pup_one.setText(strTime);

        TextView tv_pup_two = customView.findViewById(R.id.tv_pup_two);
        tv_pup_two.setText(strTime);

        ArrayList<TimeArrayBean> myBeans = new ArrayList<>();

        //确认
        TextView tv_confirm = customView.findViewById(R.id.tv_confirm);
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPupBeans != null && mPupBeans.size() > 0) {
                    for (int i = 0; i < mPupBeans.size(); i++) {
                        if (mCopyBeans != null && mCopyBeans.size() <= i) {
                            continue;
                        }
                        TimeArrayBean bean = mCopyBeans.get(i);
                        myBeans.add(bean);
                        if (bean.mIsAllDay) {
                            bean.mIsAllDay = false;
                            bean.getArrs().clear();
                            bean.getArrs().add(mStartEnd);
                        } else {
                            for (int j = 0; j < bean.getArrs().size(); j++) {
                                String str = bean.getArrs().get(j);
                                String[] strings = str.split("-");
                                String strSt = strings[0];
                                String strEn = strings[1];
                                try {
                                    int beanStart = dateToMinute(sdf.parse(strSt));
                                    int beanEnd = dateToMinute(sdf.parse(strEn));
                                    if (beanStart <= mStartTime && beanEnd >= mEndTime) {
                                        bean.getArrs().remove(j);
                                        bean.getArrs().add(mStartEnd);
                                    }
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
                popupWindow.dismiss();
                Intent data = new Intent();
                data.putParcelableArrayListExtra("beans", myBeans);
                if (quantum_time != null) {
                    handApplication(myBeans);
                }
                setResult(Activity.RESULT_OK, data);
                finish();
            }
        });


        //取消
        TextView tv_cancel = customView.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    private String jToStr(int j) {
        Calendar date = Calendar.getInstance();
        date.set(Calendar.HOUR_OF_DAY, 0);
        date.set(Calendar.MINUTE, 0);
        date.set(Calendar.SECOND, 0);
        long timeStamp = date.getTimeInMillis();
        timeStamp = timeStamp + j * 30 * 60 * 1000;
        String str = sdf.format(new Date(timeStamp));
        return str;
    }

    private OptionsPickerView mPv_time;
    private ArrayList<CardBean> cardItems = new ArrayList<>();
    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    private ArrayList<RepeatTimeBean> repeatTimeBeans = new ArrayList<>();

    private int dateToMinute(Date date) {
        return date.getHours() * 60 + date.getMinutes();
    }


    @Override
    public void receiveSessionState(HiCamera hiCamera, int i) {

    }

    @Override
    public void receiveIOCtrlData(HiCamera arg0, int arg1, byte[] arg2, int arg3) {
        if (arg0 != mMyCamera) return;
        Bundle bundle = new Bundle();
        bundle.putByteArray(HiDataValue.EXTRAS_KEY_DATA, arg2);
        Message msg = Message.obtain();
        msg.what = HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL;
        msg.obj = arg0;
        msg.arg1 = arg1;
        msg.arg2 = arg3;
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL:
                    if (msg.arg2 == 0) {//成功
                        handIOCTRLSuccess(msg);
                    } else {//失败
                    }
                    break;
            }
        }
    };


    private void handIOCTRLSuccess(Message msg) {
        Bundle bundle = msg.getData();
        byte[] data = bundle.getByteArray(HiDataValue.EXTRAS_KEY_DATA);
        switch (msg.arg1) {
            case HiChipDefines.HI_P2P_GET_REC_AUTO_SCHEDULE:
                quantum_time = new HiChipDefines.HI_P2P_QUANTUM_TIME(data);
                break;
            case HiChipDefines.HI_P2P_SET_REC_AUTO_SCHEDULE:
                Log.i("tedu", "--ADDTIMEDOMAIN--设置了时间段了--");
                //dismissjuHuaDialog();
                break;
        }
    }


}
